// DBManager.h: interface for the DBManager class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_DBMANAGER_H__0D3D0736_FA83_468F_A772_A886FC41FE6C__INCLUDED_)
#define AFX_DBMANAGER_H__0D3D0736_FA83_468F_A772_A886FC41FE6C__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "FeedGroup.h"
#include "RSSFeed.h"
#include "RSSParser.h"

class AutoDBThreadProtector{
public:
	AutoDBThreadProtector(CRITICAL_SECTION* cs){
		m_pcs=cs;
		EnterCriticalSection(m_pcs);
	}
	~AutoDBThreadProtector(){
		LeaveCriticalSection(m_pcs);
	}
private:
	CRITICAL_SECTION* m_pcs;
};

// used to operate on the database
class DBManager  
{
	friend class AutoDBCloser;
protected:
	DBManager();
	static DBManager* pInstance;
public:
	static DBManager* Instance();
	bool PrepareStmt();
	virtual ~DBManager();
	
	bool ConnectDB();
	void CloseDB();
	bool InsertAFeed(RSSFeed* pFeed);
	bool SetFeedID(RSSFeed* pFeed);
	bool InsertAGroup(FeedGroup* pGroup);
	bool SetGroupID(FeedGroup* pGroup);
	FeedGroup* CreateGroupFromID(int nID);
	RSSFeed* CreateFeedFromID(int nID);
	void GetChildrenGroups(int nID, vector<int>& Children);
	void GetChildrenFeeds(int nID, vector<int>& Children);

	bool DeleteAFeed(RSSFeed* pFeed);
	bool DeleteAFeed(int nID);
	bool DeleteAGroup(FeedGroup* pGroup);
	bool DeleteAGroup(int nID);

	bool GetFeedUrl(int nID,string &strUrl);
	bool InsetItems(int nID, vector<RSSItem>* pItems);
	bool GetItems(int nID, vector<RSSItem>& Items);
	bool GetItems(RSSFeed* pFeed, vector<RSSItem>& Items);

	int GetFeedIDByUrl(const char* strURL);

private:
	sqlite3 *m_db;
	std::string m_strDBErrMsg;
	sqlite3_stmt* m_stmtInsertFeed;
	sqlite3_stmt* m_stmtInsertGroup;
	sqlite3_stmt* m_stmtSelectFeedID;
	sqlite3_stmt* m_stmtSelectGroupID;
	sqlite3_stmt* m_stmtSelectFeedFromID;
	sqlite3_stmt* m_stmtSelectGroupFromID;
	sqlite3_stmt* m_stmtSelectChildrenGroups;
	sqlite3_stmt* m_stmtSelectChildrenFeeds;
	
	sqlite3_stmt* m_stmtDeleteFeed;
	sqlite3_stmt* m_stmtDeleteGroup;

	sqlite3_stmt* m_stmtInsertItem;
	sqlite3_stmt* m_stmtSelectItem;
	static const char* DBFile;

	CRITICAL_SECTION m_cs;
};



#endif // !defined(AFX_DBMANAGER_H__0D3D0736_FA83_468F_A772_A886FC41FE6C__INCLUDED_)
